﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CommClass;

namespace DMS
{
    public partial class FrmCardReaderAdd : Form
    {
        CardReader _CardReader = new CardReader();

        public FrmCardReaderAdd()
        {
            InitializeComponent();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void comboBox2_DrawItem(object sender, DrawItemEventArgs e)
        {

        }

        private void FrmCardReaderAdd_Load(object sender, EventArgs e)
        {
            cmbBaudrate.SelectedIndex = 0;
            DataView DV = new DataView();
            DV = App.SiteGetList();
            cmbSiteList.DataSource = DV;
            cmbSiteList.DisplayMember = "SiteName";
            cmbSiteList.ValueMember = "SiteID";
            cmbSiteList.SelectedIndex = 0;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            ///todo: 串口不正确时也返回正确连接状态
            if (string.IsNullOrEmpty(txtComPort.Text))
            {
                MessageBox.Show("请输入端口号！");
                txtComPort.Focus();
                return;
            }
            _CardReader.ComPort = int.Parse(txtComPort.Text);
            _CardReader.BaudRate = int.Parse(cmbBaudrate.Text);
            if (_CardReader.Connect())
            {
                _CardReader.Beep(10, 1);
                _CardReader.Flash(10, 1);
                _CardReader.GetDeviceSerialNumber();
                btnAdd.Enabled = true;
            }
            else
            {
                MessageBox.Show(_CardReader.Message);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtDeviceNumber.Text))
            {
                MessageBox.Show("请输入读卡器编号！");
                txtDeviceNumber.Focus();
                return;
            }
            _CardReader.DeviceNumber = txtDeviceNumber.Text;
            if (App.CardReaderAdd(_CardReader, int.Parse(cmbSiteList.SelectedValue.ToString())))
            {
                MessageBox.Show("成功添加读卡器!");
                DialogResult = DialogResult.OK;
                Close();
            }
            else
            {
                MessageBox.Show(App.Messages[0]);
            }
        }

        private void FrmCardReaderAdd_FormClosed(object sender, FormClosedEventArgs e)
        {
            _CardReader.DisConnect();
        }
    }
}
